import React, { useEffect, useRef, useState } from 'react'
import { ProTable } from '@ant-design/pro-components'
import { useModel, history } from '@umijs/max'
import { PlusOutlined, LinkOutlined } from '@ant-design/icons'
import copy from 'copy-to-clipboard'
import dayjs from 'dayjs'
import { Button, App, Input, Space, Form, Select, Radio } from 'antd'
import CardTab from '@/components/CardTab'
const { TextArea } = Input

export default () => {
  const { GetPageList, GetShortUrl, SetPageRemark, AddPage, DelPage } = useModel('PageDecoration')
  const { GetChannels } = useModel('Global')
  const { message, modal } = App.useApp()
  const tableRef = useRef()
  const [currentPage, setCurrentPage] = useState(1) //  当前页码
  const [pageSize, setPageSize] = useState(10) //  每页数量
  const [tabList, setTabList] = useState([]) // tab列表
  const [loading, setLoading] = useState(false) // 加载状态

  const [remarkFormRef] = Form.useForm()
  const [createActivityFormRef] = Form.useForm()

  const [currentTab, setCurrentTab] = useState({
    label: 'mp-alipay',
    name: '支付宝'
  }) // 当前tab

  useEffect(() => {
    getChannelsList()
  }, [])

  // 获取渠道列表
  const getChannelsList = async () => {
    const res = await GetChannels()
    if (res) {
      setTabList(res)
    }
  }

  // 编辑优惠券
  const handleEdit = async row => {
    if (row.page_type === 'home') history.push(`/shopDecoration`)
    if (row.page_type === 'activity') history.push(`/activityEditor?currentTab=${currentTab.label}&pageId=${row.id}`)
  }

  // 备注
  const handleRemarks = async row => {
    modal.confirm({
      title: '备注',
      icon: null,
      okText: '保存',
      cancelText: '取消',
      content: (
        <div>
          <Form
            initialValues={{
              remark: row.remarks
            }}
            form={remarkFormRef}
            name='remarkForm'
          >
            <Form.Item name='remark' label='备注' rules={[{ required: true, message: '请输入备注内容！' }]}>
              <TextArea placeholder='请输入' />
            </Form.Item>
          </Form>
        </div>
      ),
      onOk: async () => {
        await remarkFormRef.validateFields()
        const { remark } = await remarkFormRef.validateFields()
        const res = await SetPageRemark({
          pageId: row.id,
          remark
        })
        if (res) {
          message.success('操作成功')
          tableRef.current.reload()
        }
      }
    })
  }

  // 复制
  const handleCopy = text => {
    copy(text)
    message.success('复制成功')
  }

  // 链接
  const handleLink = async row => {
    setLoading(true)
    let obj = {
      home: {
        page: 'pages/index/index',
        params: {}
      },
      activity: {
        page: 'pages/other/activityTopic/activityTopic',
        params: {
          pageId: row.id
        }
      }
    }

    // 根据 params 遍历生成对应的入参
    let query = ''
    // eslint-disable-next-line guard-for-in
    for (let key in obj[row.page_type].params) {
      query += `${key}=${obj[row.page_type].params[key]}&`
    }
    // 去掉最后一个 &
    if (query) {
      query = query.substring(0, query.length - 1)
    }

    const alipayBaseUrl = 'alipays://platformapi/startapp?appId='

    const res = await GetShortUrl({
      type: 'page',
      relateId: row.id,
      pageUrl: `${alipayBaseUrl}$appID&page=${obj[row.page_type].page}${query ? '?' + query : ''}` //长链接信息 $appID：支付宝应用appid占位符
    })

    if (res) {
      setLoading(false)

      // 外部推广链接
      const promotionLink = window.location.origin + '/applet/' + res.token

      // alipay 链接
      const alipayLink = `${alipayBaseUrl}${res.appId}&page=${obj[row.page_type].page}${query ? '?' + query : ''}`

      modal.info({
        title: '链接',
        okText: '关闭',
        icon: null,
        content: (
          <div>
            <p>外部推广链接 : </p>
            <Space.Compact
              style={{
                width: '100%'
              }}
            >
              <Input value={promotionLink} addonBefore={<LinkOutlined />} />
              <Button type='primary' onClick={() => handleCopy(promotionLink)}>
                复制
              </Button>
            </Space.Compact>

            <p>alipay链接 : </p>
            <Space.Compact
              style={{
                width: '100%'
              }}
            >
              <Input value={alipayLink} addonBefore={<LinkOutlined />} />
              <Button type='primary' onClick={() => handleCopy(alipayLink)}>
                复制
              </Button>
            </Space.Compact>
          </div>
        )
      })
    }
  }

  // tab点击事件
  const handleTabClick = ({ label, name }) => {
    setCurrentTab({ label, name })
    // console.log('label========', label)
    // console.log('name========', name)
    tableRef.current.reload()
  }

  // 新建活动
  const handleCreateActivity = () => {
    modal.confirm({
      title: '新增活动专题页',
      icon: null,
      width: 600,
      okText: '保存',
      cancelText: '取消',
      content: (
        <div>
          <Form
            labelCol={{ span: 4 }}
            initialValues={{
              plt: currentTab.label,
              pageStatus: 1
            }}
            form={createActivityFormRef}
            name='createActivityForm'
          >
            <Form.Item name='pageName' label='名称' rules={[{ required: true, message: '请输入名称！' }]}>
              <Input placeholder='请输入' />
            </Form.Item>

            <Form.Item name='pageStatus' label='状态' rules={[{ required: true, message: '请选择状态！' }]}>
              <Radio.Group>
                <Radio value={1}>开启</Radio>
                <Radio value={0}>关闭</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item name='remark' label='备注' rules={[{ required: true, message: '请输入备注内容！' }]}>
              <TextArea placeholder='请输入' />
            </Form.Item>
          </Form>
        </div>
      ),
      onOk: async () => {
        await createActivityFormRef.validateFields()
        const values = await createActivityFormRef.validateFields()

        const res = await AddPage({
          ...values,
          plt: currentTab.label,
          pageType: 'activity'
        })

        if (res) {
          message.success('操作成功')
          tableRef.current.reload()
        }
      }
    })
  }

  // 删除活动
  const handleDelete = row => {
    modal.confirm({
      title: '删除',
      icon: null,
      content: '确定删除吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const res = await DelPage({
          pageId: row.id
        })
        if (res) {
          message.success('操作成功')
          tableRef.current.reload()
        }
      }
    })
  }

  const columns = [
    {
      title: '页面名称',
      dataIndex: 'page_name',
      hideInSearch: true,
      width: 200
    },
    {
      title: '页面状态',
      dataIndex: 'status_text',
      width: 80
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 200,
      align: 'center',
      valueType: 'dateTimeRange',
      render: (_, record) => <div>{record.created_at}</div>,
      search: {
        transform: value => {
          return {
            start: dayjs(value[0]['$d']).format('YYYY-MM-DD HH:mm:ss'),
            end: dayjs(value[1]['$d']).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      }
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      width: 200,
      align: 'center',
      hideInSearch: true
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      align: 'center',
      hideInSearch: true
    },
    {
      title: '操作',
      key: 'option',
      width: 280,
      valueType: 'option',
      fixed: 'right',
      render: (_, row, index, action) => {
        let { is_ended, can_delete, show_type } = row
        return (
          <>
            <Button type='link' key='edit' onClick={() => handleEdit(row)}>
              编辑
            </Button>
            <Button type='link' key='remarks' onClick={() => handleRemarks(row)}>
              备注
            </Button>
            <Button loading={loading} type='link' key='link' onClick={() => handleLink(row)}>
              链接
            </Button>
            <Button type='link' key='delete' danger onClick={() => handleDelete(row)}>
              删除
            </Button>
          </>
        )
      }
    }
  ]

  return (
    <ProTable
      actionRef={tableRef}
      request={async params => {
        const filters = {
          status: params.status,
          created_at_start: params.start,
          created_at_end: params.end
        }

        const param = {
          page: params.current,
          page_size: params.pageSize,
          plt: currentTab.label,
          ...filters
        }

        setCurrentPage(params.current)
        setPageSize(params.pageSize)

        const res = await GetPageList(param)

        return {
          data: res.data,
          success: true,
          total: res.total
        }
      }}
      pagination={{
        pageSize: pageSize,
        current: currentPage
      }}
      rowKey='id'
      scroll={{ x: 'max-content' }}
      columns={columns}
      headerTitle={
        <Space direction={'vertical'}>
          <Button type='primary' icon={<PlusOutlined />} onClick={() => handleCreateActivity()}>
            新建活动
          </Button>
          <CardTab tabClick={handleTabClick} tabList={tabList} isPrompt={false} />
        </Space>
      }
      search={{
        defaultCollapsed: false,
        labelWidth: 'auto',
        span: 6
      }}
    />
  )
}
